package com.conn3cted.phrasebook.web;

import java.io.IOException;
import java.net.URLConnection;
import java.util.Collection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.conn3cted.phrasebook.domain.Person;

@RequestMapping("/people2")
@Controller
public class Person2Controller {

	Log log = LogFactory.getLog(this.getClass());

	@ModelAttribute("people")
    public Collection<Person> populatePeople() {
        return Person.findAllPeople();
    }
	
	@RequestMapping(params = "list", method = RequestMethod.GET)
    public String createForm(Model uiModel) {
        return "people2/list";
    }
	
	@RequestMapping(value = "fileupload", method = RequestMethod.POST)
	protected String onSubmit(@RequestParam("file") MultipartFile file, @RequestParam("pId") long pId) throws Exception {
 
		Person person = Person.findPerson(pId);
		if (!file.isEmpty() && person != null) {
	        try {
	            byte[] fileBytes = file.getBytes();
	            person.setFile(fileBytes);
	            person.setFileContentType(URLConnection.guessContentTypeFromName(file.getName()));
	            person.merge();
	        } catch (IOException e) {
	            log.error(e);
	        }
	    }
		
		return "people2/list";
	}
}
